import Taro from '@tarojs/taro';
import {Image, View, ScrollView, Text, Button, RichText} from '@tarojs/components';
import {AtTabs, AtTabsPane} from 'taro-ui';
import {connect} from '@tarojs/redux';
import {request, unite} from '../../../utils/index';
import './trainDetail.scss';
import SelectList from "../../../components/select-list/selectList";
import paiming from '../../../asset/images/plate.png';
import dushu from '../../../asset/images/course.png';
import none from "../../../asset/images/none.png";
import Go from "../../../asset/images/go.png";
import AiIn from "../../../asset/images/ai_in.png";
import Ai from "../../../asset/images/ai.png";
import Fb from "../../../asset/images/fb.png";
import CanIn from "../../../asset/images/can_in.png";
import Can from "../../../asset/images/can.png";


class TrainDetail extends Taro.Component {
    config = {
        navigationBarTitleText: '教练详情',
        navigationBarBackgroundColor: '#ffffff',
        enablePullDownRefresh: true
    };

    state = {
        page: 1,
        type: 1, //1教练详情  2课程
        classDate: '', //时间
        detailDate: [], //数据接口
        listData: [], //课程列表
        mordIs: null,
        current: 0,
        homeData: [], //动态列表
        moreStatus: false, //更多收起
    };

    temp = {
        isLoading: false,
    };

    componentDidMount() {
        const {setClassDate} = this.props;
        console.log(setClassDate + 'setClassDate');
        this.setState({
            classDate: setClassDate
        }, () => {
            this.init();
        })
    }

    init = () => {
        const {classDate} = this.state;
        const option = this.$router.params;
        const params = {
            url: '/wx/firstPage/getCoachDetail',
            data:{
                // accessToken: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJUaGlzIGlzIEhlbGxvLVVDb2FjaCBUb2tlbiIsImF1ZCI6Ik1JTkktQVBQIiwiVXNlckFjY2Vzc1Rva2VuIjoie1widXNlcklkXCI6MTI4MjIyNTYwNTI2MTEzNTg3MyxcIm9wZW5JZFwiOlwibzk4Zno1TFhpMlFXanRvUmtNOG96N1NtM280UVwiLFwiYWNjZXNzVG9rZW5cIjpcIndnVWxRRHRrOTFVVFRYZ3ZRSDgya3dcXHUwMDNkXFx1MDAzZFwifSIsImlzcyI6IkhlbGxvLVVDb2FjaCIsImV4cCI6MTU5NjI1ODM2MiwiaWF0IjoxNTk2MjUxMTYyfQ.MTuVtw7WR6okct_tGaafMKueE0PGzKds2uB4y_HXmIk",
                coachId: option.id,
                classDate: classDate,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            detailDate: res.data,
                            listData: res.data.classDispatchInfos
                        })
                    }
                }
            }
        })
    };

    //教练收藏 取消收藏
    collect = () => {
        const {detailDate} = this.state;
        if (detailDate.collectionStatus == 0) {
            const params = {
                url: '/wx/collection/save',
                data:{
                    collectionTypeCode: '02', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: detailDate.coachId,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        unite.showToast('收藏成功');
                        this.init() //获取教练列表
                    }
                }
            })
        } else {
            const params = {
                url: '/wx/collection/deleteById',
                data:{
                    collectionTypeCode: '02', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: detailDate.coachId,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        unite.showToast('已取消收藏');
                        this.init() //获取教练列表
                    }
                }
            })
        }
    };

    //跳转课程详情
    skipCourseDetail = (classId, dispatchId) => {
        Taro.navigateTo({
            url: '../course-detail/courseDetail?classId=' + classId + '&dispatchId=' + dispatchId,
        })
    };

    getTimers = (time, index) => {
        this.setState({
            classDate: time,
            current: index,
        }, () => {
            this.init() //获取教练列表
        });
    };

    tabsClick = (is) => {
        const {getData} = this.props;
        let timer = getData.weekDays;
        this.setState({
            current: is,
            classDate: timer[is].classDate
        }, () => {
            this.init() //获取教练列表
        });
    };

    mordStatus = (is) => {
        const {mordIs} = this.state;
        this.setState({
            mordIs: is == mordIs ? null : is
        })
    };

    //跳转教室详情
    skipClassRoomDetail = (id, avatar, roomName, address, latitude, longitude) => {
        Taro.navigateTo({
            url: `../classroom-detail/classroomDetail?id=${id}&avatar=${avatar}&roomName=${roomName}&address=${address}&latitude=${latitude}&longitude=${longitude}`
        })
    };

    //分享
    onShareAppMessage () {
        const option = this.$router.params;
        return {
            title: '动态镜子',
            path:  `pages/index/train-detail/trainDetail?id=${option.id}`
        }
    }

    //选择
    skipSelect = (ix) => {
        this.setState({
            type: ix
        }, () => {
            if (ix == 1) {
                this.init();
            } else {
                this.myList(); //动态列表
            }
        })
    };

    //请求动态列表
    myList = () => {
        const {page} = this.state;
        const option = this.$router.params;
        this.temp.isLoading = true;
        const params = {
            url: '/momments/coachMements',
            data:{
                coachId: option.id,
                pageNo: page,
                pageSize: 10,
            }
        };
        request(params).then(res => {
            this.temp.isLoading = false; //防止多次上拉加载
            if (res) {
                if(res.code == 200){
                    this.setState((prevState)=>({
                        homeData: page === 1 ? res.data : prevState.homeData.concat(res.data),
                    }));
                    //判断是否为最后一页
                    if (res.data.length < 10) {
                        this.temp.isLoading = true; //
                    }
                }
            }
        })
    };

    //动态点赞 取消赞
    isShouc = (isLike, dtId, index, e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        //   isLike 0未点赞，1已点赞
        if(this.temp.onDisable) return;
        this.temp.onDisable = true;
        const params = {
            url: '/momments/likeOpt',
            data:{
                opt:  isLike == 0 ? 1 : 0,
                type: 0,
                uid: dtId,
            }
        };
        request(params, '', '', '', false).then(res => {
            this.temp.onDisable = false; //防止多次
            if (res) {
                if(res.code == 200) {
                    this.setState((prevState) => {
                        if (isLike == 0) { //未点赞
                            prevState.homeData[index].likeCount = Number(prevState.homeData[index].likeCount) + 1;
                            prevState.homeData[index].isLike = 1;
                        } else { //已点赞
                            prevState.homeData[index].likeCount = Number(prevState.homeData[index].likeCount) - 1;
                            prevState.homeData[index].isLike = 0;
                        }
                        return{
                            homeData: prevState.homeData
                        }
                    })
                }
            }
        })
    };

    //跳转详情页
    skipDetail = (id, dtId) => {
        //id 课程id dtId 动态id
        Taro.navigateTo({
            url: `../../home/detail/detail?id=${id}&dtId=${dtId}`
        })
    };

    getMore = () => {
        this.setState(prevState => ({
            moreStatus: !prevState.moreStatus
        }));
    };

    //底部上拉刷新加载更多
    onReachBottom() {
        const {type} = this.state;
        if (type == 2){
            if(this.temp.isLoading) return;
            this.setState((pervState) =>({
                page: pervState.page + 1
            }),() => {
                this.myList();
            })
        }
    };

    render() {
        const {detailDate, listData, mordIs, current, classDate, type, homeData, moreStatus} = this.state;
        const {getData} = this.props;
        return (
            <View className="page">
                <View className="course-logo">
                    <Image className="keep-head-img" src={detailDate.avatar} mode="widthFix"/>
                    <Image className="head-ai" onClick={this.collect} src={detailDate.collectionStatus != 0 ? AiIn : Ai} mode="aspectFit"/>
                    <Button className="head-fb"  open-type="share">
                        <Image className="head-fb-img" src={Fb} onClick={this.onShareAppMessage} mode="aspectFit"/>
                    </Button>
                </View>
                <View className="course-head">
                    <View className="select-items-wrap flex-lr">
                        <View className={`items-list ${type == 1 ? 'items-list-avtive' : ''}`} onClick={this.skipSelect.bind(this, 1)}>
                            <View>教练信息</View>
                            <View className="heng"></View>
                        </View>
                        <View className={`items-list ${type == 2 ? 'items-list-avtive' : ''}`} onClick={this.skipSelect.bind(this, 2)}>
                            <View>动态</View>
                            <View className="heng"></View>
                        </View>
                    </View>
                    {type == 1 &&(
                        <View className="course-head-wrap">
                            <View className="head-wrap-name">
                                <View className="head-wrap-left">{detailDate.coachName}</View>
                            </View>
                            <View className="xss-content">
                                <RichText className={`head-wrap-text ${moreStatus ? '' : 'shuzi'}`} nodes={detailDate.description}></RichText>
                                <View className="gengduo-name" onClick={this.getMore}>{moreStatus ? '收起' : '更多'}</View>
                            </View>
                        </View>
                    )}
                </View>
                {type == 1 &&(
                    <View className="course-content">
                        <View className="course-content-wrap flex-l">
                            <View className="content-wrap-list">
                                <Image className="list-head-img" src={paiming}/>
                                <View className="list-head-text">{detailDate.rank ? '排名' + detailDate.rank : '暂无排名'}</View>
                            </View>
                            <View className="content-wrap-list">
                                <Image className="list-head-img" src={dushu}/>
                                <View>累计上课量，共{detailDate.totalMinutes || 0}分钟</View>
                            </View>
                        </View>
                    </View>
                )}
                {type == 1 &&(
                    <View className="zywj-wrap">
                        <View className="shop-sort-bottom">
                            <ScrollView
                                className='scrollview'
                                scrollX
                                scrollLeft
                                scrollWithAnimation
                            >
                                <SelectList onTimer={this.getTimers} getClassDate={classDate}/>
                            </ScrollView>
                        </View>
                        <View className="shop-sort-shop">
                            {getData.weekDays &&(
                                <AtTabs className="com-tabs" current={current} tabList={getData.weekDays} onClick={this.tabsClick.bind(this)}>
                                    {getData.weekDays && getData.length != 0 && getData.weekDays.map((va, ixs) => (
                                        <AtTabsPane current={current} key={ixs} index={ixs+1} >
                                            {listData && listData.length != 0 && (
                                                <ScrollView
                                                    className="content-view"
                                                    scrollY
                                                    upperThreshold={3}
                                                    scroll-with-animation
                                                    enhanced
                                                    show-scrollbar
                                                    paging-enabled
                                                    fast-deceleration
                                                    lowerThreshold={3}
                                                >
                                                    {listData && listData.length != 0 && listData.map((item, index) => (
                                                        <View className={`keep-contents ${(Number(listData.length) -1) == index ? 'keep-contents-db' : ''}`} key={index}>
                                                            <View className="keep-heads" >
                                                                <View className="keep-head-tops" onClick={this.skipClassRoomDetail.bind(this, item.roomId,item.avatar,item.roomName,item.address,item.latitude, item.longitude)}>
                                                                    <View className="flex-l">
                                                                        <Image className="keep-img" src={item.avatar}/>
                                                                        <View>{item.roomName}</View>
                                                                    </View>
                                                                    {/*<View className="keep-head-bt">*/}
                                                                    {/*    <View>{item.roomName}</View>*/}
                                                                    {/*    <View className="text-address text-overflow">{item.address}</View>*/}
                                                                    {/*</View>*/}
                                                                    <View className="keep-head-more flex-r" onClick={this.goToMap.bind(this, item.roomName,item.address,item.latitude, item.longitude)}>
                                                                        <Image className="icon-img" src={Go}/>
                                                                        <View>去这里</View>
                                                                    </View>
                                                                </View>
                                                                <View className={`keep-content ${index == mordIs ? 'keep-content-height' : ''}`}>
                                                                    {item.hotClasses && item.hotClasses.map((value, is) => (
                                                                        <View className="keep-content-list-item" key={is} onClick={this.skipCourseDetail.bind(this, value.classId, value.dispatchId, value.reservedStatus)}>
                                                                            <Image className="list-img" src={value.avatar} onClick={this.skipTrainDetail.bind(this, value.coachId)}/>
                                                                            <View className={`list-centent-left-wrap ${item.hotClasses.length == (is+1) ? 'list-centent-left-wrap-heng' : ''}`}>
                                                                                <View className="list-centent">
                                                                                    <View className="name">{value.className}</View>
                                                                                    <View className="timer">{value.classBeginTime}-{value.classEndTime} <Text className="text">￥{value.price}/节</Text></View>
                                                                                    <View className="type flex-l">
                                                                                        {/*<View className="list-top-left flex-center text-overflow">{value.reservedInfo}</View>*/}
                                                                                        {value.labelNames.map((items, indexs) => (
                                                                                            <View className="kepp-gg flex-center" key={indexs}>{items}</View>
                                                                                        ))}
                                                                                    </View>
                                                                                </View>
                                                                                <View className={`list-right-bt ${value.reservedStatus == 0 ? '' : 'list-right-bt-ym'}`}>{value.reservedStatus == 0 ? '预约' : '已约满'}</View>
                                                                            </View>
                                                                        </View>
                                                                    ))}
                                                                </View>
                                                                {item.hotClasses.length >= 4 && (
                                                                    <View className="jiazaigengduo flex-center" onClick={this.mordStatus.bind(this, index)}>{index == mordIs ? '收起' : '查看更多'}</View>
                                                                )}
                                                            </View>
                                                        </View>
                                                    ))}
                                                </ScrollView>
                                            )}
                                            {(!listData || listData.length == 0) &&(
                                                <View className="none" style="margin: 0 auto;">
                                                    <Image src={none}/>
                                                    <View>暂无数据</View>
                                                </View>
                                            )}
                                        </AtTabsPane>
                                    ))}
                                </AtTabs>
                            )}
                        </View>
                    </View>
                )}
            {/*    动态*/}
                {type == 2 &&(
                    <View className="dt-content-wrap">
                        <View className="home-list-content flex-top">
                            {homeData && homeData.map((item, index) => (
                                <View className="home-list home-list-next" key={index} onClick={this.skipDetail.bind(this, item.dispatchId, item.momentId)}>
                                    <View className="img-ck">
                                        <Image className="imgs" src={item.imgs[0].imgUrl} mode="aspectFill"/>
                                    </View>
                                    <View className="home-details">
                                        <View className="home-name text-overflow-two">{item.title}</View>
                                        <View className="flex-lr detail-title">
                                            <View className="flex-l">
                                                <Image className="heads" src={item.authorAvatar}/>
                                                <View className="text-name text-overflow">{item.authorName}</View>
                                            </View>
                                            <View className="flex-r" onClick={this.isShouc.bind(this, item.isLike, item.momentId, index)}>
                                                <Image className="cans" src={item.isLike == 1 ? CanIn : Can} mode="aspectFit"/>
                                                <View>{item.likeCount}</View>
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            ))}
                        </View>
                        {homeData && homeData.length == 0 &&(
                            <View className="none" style="margin: 0 auto;">
                                <Image src={none}/>
                                <View>暂无数据</View>
                            </View>
                        )}
                    </View>
                )}
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {setClassDate, getData} = state;
    return {
        setClassDate,
        getData
    }
};

const mapDispatchToProps = {
};
export default connect(mapStateToProps, mapDispatchToProps)(TrainDetail);



